package io.renren.modules.biz.service.impl;

import io.renren.common.exception.RRException;
import io.renren.common.utils.HttpContextUtils;
import io.renren.common.utils.IPUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.ProjectConstant;
import io.renren.common.utils.Query;
import io.renren.common.validator.Assert;
import io.renren.modules.biz.dao.MemberDao;
import io.renren.modules.biz.entity.CountDto;
import io.renren.modules.biz.entity.MemberEntity;
import io.renren.modules.biz.entity.TeamEntity;
import io.renren.modules.biz.service.MemberService;
import io.renren.modules.biz.service.TeamService;
import io.renren.modules.biz.service.TokenService;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

	@Autowired
	TeamService teamService;

	@Autowired
	TokenService tokenService;

	@SuppressWarnings("unchecked")
	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String mobile = (String) params.get("mobile");
		String id = (String) params.get("id");
		String all = (String) params.get("all");
		List<Long> ids = (List<Long>) params.get("ids");
		Page<MemberEntity> page = this.selectPage(new Query<MemberEntity>(params).getPage(),
				new EntityWrapper<MemberEntity>().eq(StringUtils.isNotBlank(mobile), "mobile", mobile).eq(StringUtils.isNotBlank(id), "id", id).in(ids != null, "id", ids).ne(all == null || "0".equals(all), "user_level", ProjectConstant.USER_LEVEL_ROBOT));

		return new PageUtils(page);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void save(MemberEntity member) {
		Assert.isTrue(this.selectCount(new EntityWrapper<MemberEntity>().eq("mobile", member.getMobile())) == 0, "手机号已注册");

		member.setRecPerson(StringUtils.isNotBlank(member.getRecPerson()) ? member.getRecPerson().toUpperCase() : null);
		member.setCode(genCode());
		member.setRegIp(IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest()));
		member.setCreateTime(new Date());
		this.insert(member);

		// 处理上级推荐人
		if (StringUtils.isNotBlank(member.getRecPerson())) {
			MemberEntity m = this.selectOne(new EntityWrapper<MemberEntity>().eq("code", member.getRecPerson()));
			Assert.notNull(m, "推荐人无效");
			TeamEntity teamEntity = new TeamEntity();
			teamEntity.setMemberId(member.getId());
			teamEntity.setHigherOne(m.getId());
			TeamEntity t = teamService.selectOne(new EntityWrapper<TeamEntity>().eq("member_id", m.getId()));
			if (t != null) {
				if (t.getHigherOne() != null) {
					teamEntity.setHigherTwo(t.getHigherOne());
					if (t.getHigherTwo() != null) {
						teamEntity.setHigherThree(t.getHigherTwo());
					}
				}
			}
			teamService.insert(teamEntity);
		}
	}

	private String genCode() {
		String code = RandomStringUtils.randomAlphanumeric(6).toUpperCase();
		if (this.selectCount(new EntityWrapper<MemberEntity>().eq("code", code)) > 0) {
			return genCode();
		}
		return code;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void changeStauts(String type, List<Long> memberIds) {
		Date now = new Date();

		if (type.equals("FH")) {

			// 封号
			for (Long memberId : memberIds) {
				MemberEntity member = new MemberEntity();
				member.setId(memberId);
				member.setUpdateTime(now);
				member.setStatus(ProjectConstant.COMMON_STATUS_DISABLE);
				this.updateById(member);

				// 移动端登录会话过期
				tokenService.expireToken(member.getId());
			}

		} else if (type.equals("JF")) {

			// 解封
			for (Long memberId : memberIds) {
				MemberEntity member = new MemberEntity();
				member.setId(memberId);
				member.setUpdateTime(now);
				member.setStatus(ProjectConstant.COMMON_STATUS_ENABLE);
				this.updateById(member);
			}

		} else {
			throw new RRException("操作失败[参数异常]");
		}
	}

	public CountDto platformStatistics(String startDate, String endDate) {
		return baseMapper.platformStatistics(startDate, endDate);
	}
}